package com.bjpowernode.crm.workbench.web.controller;

import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.utile.DateTimeUtil;
import com.bjpowernode.crm.utile.HandleFlag;
import com.bjpowernode.crm.utile.UUIDUtil;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.ActivityRemark;
import com.bjpowernode.crm.workbench.service.ActivityRemarkService;
import com.bjpowernode.crm.workbench.service.ActivityService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName:ActivityController
 * package:com.bjpowernode.crm.workbench.web.controller
 * Description:
 *
 * @date: 2022-06-01 22:57
 * @author：lin
 */
@Controller
@RequestMapping("/workbench/activity")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityRemarkService remarkService;

    @Autowired
    private UserService userService;





    //跳转到市场活动列表
    //workbench/activity/toActivity.do
    @RequestMapping("toActivity.do")
    public String toActivity(){



        return "/workbench/activity/index";
    }


    //	url:"workbench/activity/getUser.do",
    @RequestMapping("/getUser.do")
    @ResponseBody
    public List getUser(){
         List<User> uList =userService.getUser();


        return uList;
    }


    //url:"workbench/activity/saveActivity.do",               //请求路径
    //提交保存市场活动数据
    @RequestMapping("saveActivity.do")
    @ResponseBody
    public Map<String,Object> saveActivity(Activity activity, HttpSession session){

         String id=UUIDUtil.getUUID();

         String createBy = ((User)session.getAttribute("user")).getName();

           String date  =DateTimeUtil.getSysTime();

           activity.setId(id);
           activity.setCreateBy(createBy);
           activity.setCreateTime(date);
           activityService.saveActivity(activity);

        return HandleFlag.successTrue();

    }

    //	url:"workbench/activity/searchActivity.do",               //请求路径
    //  查询市场活动
    /*@RequestMapping("/searchActivity.do")
    @ResponseBody
    public Map<String,Object> searchActivity(String owner,String name,String startDate,String endDate,String pageNo, String pageSize){


          int pageNoSer=  Integer.valueOf(pageNo) ;
          int pageSizeSer=  Integer.valueOf(pageSize) ;

          int skipCount = (pageNoSer-1)*pageSizeSer;

          Map<String,Object> map = new HashMap<>();
          map.put("owner",owner);
          map.put("name",name);
          map.put("startDate",startDate);
          map.put("endDate",endDate);
          map.put("skipCount",skipCount);
          map.put("pageSizeSer",pageSizeSer);

           Map<String,Object> pageMap = activityService.searchActivity(map);

        return pageMap;
    }*/


    //	url:"workbench/activity/searchActivity.do",               //请求路径
    //  查询市场活动
    @RequestMapping("/searchActivity.do")
    @ResponseBody
    public Map<String,Object> searchActivity(String owner,String name,String startDate,String endDate,String pageNo,
                                 String pageSize){


          int pageNoSer=  Integer.valueOf(pageNo) ;
          int pageSizeSer=  Integer.valueOf(pageSize) ;

          int skipCount = (pageNoSer-1)*pageSizeSer;

          Map<String,Object> map = new HashMap<>();
          map.put("owner",owner);
          map.put("name",name);
          map.put("startDate",startDate);
          map.put("endDate",endDate);
          map.put("skipCount",skipCount);
          map.put("pageSizeSer",pageSizeSer);

           Map<String,Object> pageMap = activityService.searchActivity(map);

        return pageMap;
    }


    //url:"workbench/activity/deleteActivity.do"
    //删除市场活动列表
    @RequestMapping("/deleteActivity.do")
    @ResponseBody
    public Map<String,Object> deleteActivity(String[] ids){

        activityService.deleteActivity(ids);

        return HandleFlag.successTrue();
    }

    //	url:"workbench/activity/toUpdateActivity.do",    //请求路径
    //查询需要更新的数据并打开更新页面
    @RequestMapping("/toUpdateActivity.do")
    @ResponseBody
    public Map<String,Object>toUpdateActivity(String id){
        Map<String,Object> map =activityService.getUserAndActivityByid(id);
        return map;

    }


    //url:"workbench/activity/updateActivity.do",    //请求路径
    //更新市场活动数据，将数据保存至数据库
    @RequestMapping("/updateActivity.do")
    @ResponseBody
    public Map<String,Object> updateActivity (Activity activity,HttpSession session){
         String editname = ((User)session.getAttribute("user")).getName();
         String editTime  = DateTimeUtil.getSysTime();
         activity.setEditBy(editname);
         activity.setEditTime(editTime);

          activityService.updateActivity(activity);

        return HandleFlag.successTrue();





    }


    //批量下载市场活动列表
    //window.location.href="workbench/activity/exportActivityAll.do"
    //window.location.href="workbench/activity/exportActivityXz.do"
    @RequestMapping("/exportActivityAll.do")
    public  void exportActivityAll(HttpServletResponse response, HttpServletRequest request) throws IOException {
       List<Activity> activityList =activityService.exportActivityAll();

        HSSFWorkbook workbook= new HSSFWorkbook();
        HSSFSheet sheet= workbook.createSheet();
        HSSFRow row= sheet.createRow(0);
        HSSFCell cell= row.createCell(0);
        cell.setCellValue("名称");
        cell= row.createCell(1);
        cell.setCellValue("所有者");
        cell= row.createCell(2);
        cell.setCellValue("开始时间");
        cell= row.createCell(3);
        cell.setCellValue("结束时间");
        Activity activity=null;

        for (int i=0 ;i<activityList.size();i++){
            activity=activityList.get(i);
            row= sheet.createRow(i+1);
            cell= row.createCell(0);
            cell.setCellValue(activity.getName());
            cell= row.createCell(1);
            cell.setCellValue(activity.getOwner());
            cell= row.createCell(2);
            cell.setCellValue(activity.getStartDate());
            cell= row.createCell(3);
            cell.setCellValue(activity.getStartDate());


        }

        //根据HTTP协议的规定，浏览器每次向服务器发送请求，都会把浏览器信息以请求头的形式发送到服务器。
        //获取请求头信息
        String browser=request.getHeader("User-Agent");
        System.out.println("browser="+browser);//firefox、Firefox、FireFox、FIREFOX、...

        //不同的浏览器接收响应头信息的所采用的的编码格式不一样：IE采用application/x-www-form-urlencoded，火狐采用ISO8859-1
        //全变成小写
        String fn=URLEncoder.encode("市场活动","UTF-8");
        if(browser.toLowerCase().indexOf("firefox")>0){

            //火狐
            fn=new String("市场活动".getBytes("utf-8"),"ISO8859-1");
        }

        //浏览器接收到响应信息之后，默认会直接打开；可以设置响应头信息，激活文件下载窗口，而不是直接打开

        response.addHeader("Content-Disposition","attachment;filename="+fn+".xls" );
        //把workbook对象写入excel文件
        OutputStream os= response.getOutputStream();
        workbook.write(os);
        //os.close();
        workbook.close();




    }

    //	window.location.href="workbench/activity/exportActivitySelect.do?"+ids
    @RequestMapping("/exportActivitySelect.do")
    public  void exportActivitySelect(String[] id ,HttpServletRequest request,HttpServletResponse response) throws IOException {
        List<Activity> activityList=activityService.searchActivityById(id);
        HSSFWorkbook workbook= new HSSFWorkbook();
        HSSFSheet sheet= workbook.createSheet();
        HSSFRow row= sheet.createRow(0);
        HSSFCell cell= row.createCell(0);
        cell.setCellValue("名称");
        cell= row.createCell(1);
        cell.setCellValue("所有者");
        cell= row.createCell(2);
        cell.setCellValue("开始时间");
        cell= row.createCell(3);
        cell.setCellValue("结束时间");
        Activity activity=null;

        for (int i=0 ;i<activityList.size();i++){
            activity=activityList.get(i);
            row= sheet.createRow(i+1);
            cell= row.createCell(0);
            cell.setCellValue(activity.getName());
            cell= row.createCell(1);
            cell.setCellValue(activity.getOwner());
            cell= row.createCell(2);
            cell.setCellValue(activity.getStartDate());
            cell= row.createCell(3);
            cell.setCellValue(activity.getStartDate());


        }
        String browser=request.getHeader("User-Agent");
        System.out.println("browser="+browser);//firefox、Firefox、FireFox、FIREFOX、...


        String fn=URLEncoder.encode("市场活动","UTF-8");
        if(browser.toLowerCase().indexOf("firefox")>0){

            //火狐
            fn=new String("市场活动".getBytes("utf-8"),"ISO8859-1");
        }

        //浏览器接收到响应信息之后，默认会直接打开；可以设置响应头信息，激活文件下载窗口，而不是直接打开

        response.addHeader("Content-Disposition","attachment;filename="+fn+".xls" );
        //把workbook对象写入excel文件
        OutputStream os= response.getOutputStream();
        workbook.write(os);
        //os.close();
        workbook.close();

    }

    //url:"workbench/activity/importActivity.do",               //请求路径
    //上传市场活动文件
    @RequestMapping("/importActivity.do")
    @ResponseBody
    public Map<String,Object> importActivity(MultipartFile activityFile,HttpSession session) throws IOException {
        Map<String,Object> retMap = new HashMap<>();
        User user= (User) session.getAttribute("user");


         InputStream inputStream= activityFile.getInputStream();
         HSSFWorkbook workbook =new HSSFWorkbook(inputStream);
          HSSFSheet sheet=workbook.getSheetAt(0);
         Activity activity= null;
         HSSFRow row=null;
         List<Activity> activityList =new ArrayList<>();

         for (int i=1;i<sheet.getLastRowNum()+1;i++){
             row=sheet.getRow(i);
             activity=new Activity();

             activity.setId(UUIDUtil.getUUID());
             activity.setCreateBy(user.getId());
             activity.setCreateTime(DateTimeUtil.getSysTime());
             activity.setOwner(user.getId());


             activity.setName(getValueFromCell(row.getCell(0)));
             activity.setStartDate(getValueFromCell(row.getCell(1)));
             activity.setEditTime(getValueFromCell(row.getCell(2)));
             activity.setCost(getValueFromCell(row.getCell(3)));
             activity.setDescription(getValueFromCell(row.getCell(4)));

             activityList.add(activity);



         }

         int count = activityService.importActivity(activityList);

         retMap.put("success",true);
         retMap.put("count",count);


         return retMap;


    }


    //处理前端数码将其转换为string 类型
    public String getValueFromCell(HSSFCell cell){
        int  cellType  =  cell.getCellType();
        String ret="";

        switch (cellType){
            case HSSFCell.CELL_TYPE_BLANK:
                ret="";
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                ret=cell.getBooleanCellValue()+"";
                break;
            case HSSFCell.CELL_TYPE_ERROR:
                ret="";
                break;
            case HSSFCell.CELL_TYPE_FORMULA:
                ret=cell.getCellFormula();
                break;
            case HSSFCell.CELL_TYPE_NUMERIC:
                ret=cell.getNumericCellValue()+"";
                break;
            case HSSFCell.CELL_TYPE_STRING:
                ret=cell.getStringCellValue();


        }

        return ret;

    }


    //'workbench/activity/detailActivity.do?id="+n.id+"';
    //跳转detail页面

  @RequestMapping("/detailActivity.do")
  public  String   detailActivity(String id, Model model){
        Activity activity=  activityService.getActivityById(id);
        List<ActivityRemark> remarkList =remarkService.searchActivityRemark(id);

        model.addAttribute("activity",activity);
        model.addAttribute("remarkList",remarkList);





        return "/workbench/activity/detail";

  }

  //url:"workbench/activity/saveActivityRemark.do",
    //保存市场活动备注表信息
  @RequestMapping("/saveActivityRemark.do")
  @ResponseBody
   public Map<String,Object> saveActivityRemark(HttpSession session, String noteContent,String activityId){
        User user = (User) session.getAttribute("user");
        ActivityRemark remark =new ActivityRemark();

        String id = UUIDUtil.getUUID();
        remark.setId(id);
        remark.setNoteContent(noteContent);
        remark.setCreateTime(DateTimeUtil.getSysTime());
        remark.setCreateBy(user.getId());
        remark.setActivityId(activityId);
        remark.setEditFlag("0");

       int count =remarkService.saveActivityRemark(remark);
       Map map= new  HashMap<>();
       map.put("code","0");
       map.put("remark",remark);
       map.put("count",count);





       return map;

  }

  //修改市场活动备注表
    // 	url:"workbench/activity/editActivityRemark.do",
    //	url:"workbench/activity/editActivityRemark.do",

    @RequestMapping("/editActivityRemark.do")
    @ResponseBody
    public Map<String,Object> editActivityRemark(String remarkId,String noteContent,HttpSession session ){
        User user= (User) session.getAttribute("user");

        ActivityRemark remark =new ActivityRemark();
        remark.setId(remarkId);
        remark.setNoteContent(noteContent);
        remark.setEditTime(DateTimeUtil.getSysTime());
        remark.setEditFlag("0");
        remark.setEditBy(user.getName());


        boolean success= remarkService.updateActivityRemark(remark);
        Map<String,Object> map = new HashMap<>();
        map.put("success",success);
        map.put("remark",remark);


        return map;
    }

    //	url:"workbench/activity/deleteActivityRemark.do",
    @RequestMapping("/deleteActivityRemark.do")
    @ResponseBody
    public Map<String,Object> deleteActivityRemark(String id){
       boolean success= remarkService.deleteActivityRemark(id);

        Map<String,Object> map =new HashMap<>();
        map.put("success",success);



        return map;
    }
























}
